package com.sxjh.uitl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.util.MapUtils;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Component
@Slf4j
public class ExcelUtils {

    /**
     * 从浏览器下载excel
     *
     * @param response                res
     * @param fileName                文件名称
     * @param includeColumnFiledNames 需要展示的字段 可以为空，默认展示全部字段
     * @param list                    表数据 不能为空
     * @param sheetName               表格名称
     * @param t                       T.class
     * @param <T>                     Class
     */
    public <T> void downLoadFromWeb(HttpServletResponse response, String fileName, Set<String> includeColumnFiledNames, List<T> list, String sheetName, Class<T> t) {
        try {
            fileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            if (CollectionUtils.isEmpty(includeColumnFiledNames)) {
                EasyExcel.write(response.getOutputStream(), t).sheet(sheetName).doWrite(list);
            } else {
                EasyExcel.write(response.getOutputStream(), t).includeColumnFieldNames(includeColumnFiledNames).sheet(sheetName).doWrite(list);
            }
        } catch (IOException e) {
            log.error("导出数据失败");
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, String> map = MapUtils.newHashMap();
            map.put("status", "failure");
            map.put("message", "下载文件失败" + e.getMessage());
            try {
                response.getWriter().println(JSON.toJSONString(map));
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }
    }
}
